﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using HandyControl.Controls;
using System.Windows;
using YJTTool.Common.Attributes;
using YJTTool.Common.Controls;
using YJTTool.Common.Events;
using HandyControl.Tools.Extension;

namespace YJTTool.Common.Helper
{
    public class LoadingMaskInterceptor
    {
        public LoadingMask _loadingMask;

        // 私有静态实例
        private static LoadingMaskInterceptor _instance;

        // 静态锁对象
        private static readonly object _lock = new object();

        // 私有构造函数，防止外部直接实例化
        private LoadingMaskInterceptor()
        {

        }

        // 单例实例访问
        public static LoadingMaskInterceptor Instance()
        {
            // 双重锁定确保线程安全
            if (_instance == null)
            {
                lock (_lock)
                {
                    if (_instance == null)
                    {
                        _instance = new LoadingMaskInterceptor();
                    }
                }
            }

            return _instance;
        }

        public async Task InterceptAsync(Func<Task> action)
        {
            LoginVisibilityEvent.Instance.PushMessage(Visibility.Visible);
            try
            {
                await action();  // 执行实际的任务
            }
            finally
            {
                LoginVisibilityEvent.Instance.PushMessage(Visibility.Collapsed);
            }
        }

        public void ExecuteWithLoadingMask(Func<Task> action)
        {
            var method = action.Method;
            var attribute = method.GetCustomAttribute<ShowLoadingMaskAttribute>();

            if (attribute != null)
            {
                _loadingMask.Show(); // 显示加载遮罩
            }

            action().ContinueWith(t => _loadingMask.Hide()); // 执行方法并在完成后隐藏遮罩
        }
    }
}
